# encoding:utf-8
"""
@Time : 2025/6/23 10:49
@Author : FUJIU
@File : model_seasonal.py
"""
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Line, Timeline

from get_data import get_data

# 调用get_data函数获取数据
data = get_data()

# 将数据转换为 DataFrame
df = pd.DataFrame(data)

# 计算季度
# 使用 apply 方法和 lambda 函数，根据月份计算所属季度
df['quarter'] = df['month'].apply(lambda x: (x - 1) // 3 + 1)

# 将季度转换为季节
def quarter_to_season(quarter):
    if quarter == 1:
        return '春'
    elif quarter == 2:
        return '夏'
    elif quarter == 3:
        return '秋'
    else:
        return '冬'

df['season'] = df['quarter'].apply(quarter_to_season)

# 按年份、季节和车型分组，计算总销量
# groupby 方法按多个列分组，然后对 sales_volume 列求和，最后通过 reset_index 重置索引
seasonal_sales = df.groupby(['year', 'season', 'model'])['sales_volume'].sum().reset_index()

# 获取所有车型
models = seasonal_sales['model'].unique()

# 选择销量最高的几个车型进行显示
top_models = seasonal_sales['model'].value_counts().nlargest(10).index.tolist()

# 创建 Line 图表
timeline = Timeline()

for year in seasonal_sales['year'].unique():
    line = (
        Line(init_opts=opts.InitOpts(width="1600px", height="400px"))
        .add_xaxis([f"{year}{season}".format(year=year, season=season) for season in seasonal_sales['season'].unique()])
    )

    # 为每个车型添加数据
    for model in top_models:
        model_data = seasonal_sales[(seasonal_sales['model'] == model) & (seasonal_sales['year'] == year)]
        line.add_yaxis(
            series_name=model,
            y_axis=model_data['sales_volume'].tolist(),
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                ]
            ),
            markline_opts=opts.MarkLineOpts(
                data=[
                    opts.MarkLineItem(type_="average", name="平均值"),
                ]
            ),
        )

    # 设置全局配置项
    line.set_global_opts(
        title_opts=opts.TitleOpts(title=f"{year}年各车型季节销量趋势图"),
        tooltip_opts=opts.TooltipOpts(trigger="axis", background_color="rgba(245, 245, 245, 0.5)"),
        legend_opts=opts.LegendOpts(pos_top="5%", pos_left="center"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(name="年份季节", axislabel_opts=opts.LabelOpts(rotate=-15)),
        yaxis_opts=opts.AxisOpts(name="销量", min_=0, max_=200000),
    )

    # 将图表添加到时间轴
    timeline.add(line, time_point=str(year))

# 设置时间轴配置
timeline.add_schema(
    is_auto_play=False,
    play_interval=2000,
)

# 渲染图表
timeline.render("model_seasonal_sales.html")